import { useEventEmitter, useMount } from "ahooks"
import { useRequest } from "alova/client"
import { lazy, useState } from 'react'
import { ModelBox } from '../Model'

import { Http } from "../Utils/Api"
import { Encrypt, IndexedDBClear } from '../Utils/IndexedDB'
import { pageStore, modelStore, drawerStore, fromStore } from '../Config/zustand'

const { hostname } = window.location

const LoginInit = () => {
    const { updateList } = pageStore()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { updateFromData, updateFromLoad } = fromStore()
    const [Template, setTemlate] = useState()
    const { send } = useRequest(data => Http(data), { immediate: false })

    useMount(() => {
        // 初始化本地缓存
        IndexedDBClear()
        sessionStorage.clear()
        localStorage.clear()
        updateList([])
        updateModel({})
        updateDrawer({})
        updateFromData({})
        updateFromLoad(false)
        // 判断进入方式
        if (hostname === 'localhost') {
            const Template = lazy(() => import(`./page/${hostname}.jsx`))
            setTemlate(Template)
        } else {
            send({ method: 'get', url: 'projects/getProjectConfigInfo', params: { WebUrl: hostname } }).then(async res => {
                const { config, key } = res
                const [configData] = config
                // isScan 是否扫码登录
                const { apiUrl, authUrl, imageUrl, client_Id, tableName, isScan } = configData
                sessionStorage.setItem('uuid', key)
                sessionStorage.setItem('API', apiUrl)
                sessionStorage.setItem('AUTH', authUrl)
                sessionStorage.setItem('IMAGE', imageUrl)
                sessionStorage.setItem('TITLE', tableName)
                const common = await Encrypt(configData, true)
                localStorage.setItem('config', common)
                const Template = lazy(() => import(`./page/${client_Id}.jsx`))
                setTemlate(Template)
            })
        }
    })

    return (
        <div className="LoginPage">
            {Template && <Template />}
            <ModelBox />
        </div>
    );
};

export default LoginInit;
